#pragma once

#include<iostream>
#include"InetAddr.hpp"
#include"Socket.hpp"
#include"Log.hpp"
#include"Connection.hpp"
#include"IOService.hpp"
#include"Reactor.hpp"
#include"Protocol.hpp"
using namespace LogModule;
using namespace SocketModule;
//用于获取链接的模块
class Listener :public Connection
 {
public:
    Listener(int port)
    :_listensock(std::make_unique<TcpSocket>())
    ,_port(port)
{
    _listensock->BuildTcpSocket(_port);
    SetSockfd(_listensock->Fd());
    SetEvents(EPOLLIN|EPOLLET);

}
int Fd()
{
    return _listensock->Fd();
}
virtual void Recever()override
{
    while(true)
    {
        InetAddr peer;
        int aerror=0;
        int sockfd=_listensock->Accept(&peer,&aerror);
        if(sockfd<0)
        {
            if(aerror==EAGAIN||aerror==EWOULDBLOCK)
            {
                LOG(LogLevel::DEBUG)<<"accept error"<<aerror;
                break;
            }
            else if(aerror==EINTR)
            {
                LOG(LogLevel::DEBUG)<<"accept interrupt by signal,continue";
                continue;
            }
            else
            {
                LOG(LogLevel::ERROR)<<"accept error"<<aerror;
                break;
            }
        }
        else
        {
            //设置非阻塞
            SetNonBlock(sockfd);
            //创建连接对象
            auto conn=std::make_shared<IOService>(sockfd);
            conn->RegisterOnMessage(HandlerRequese);
            Owner()->InsertConnection(conn);
        }

    }
}
virtual void Sender()override
{

}
virtual void Excepter()override
{

}
~Listener()
{
    
    _listensock->Close();
}
    private:
    std::unique_ptr<Socket> _listensock;
    int _port;
};